package com.powernode.handle;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.powernode.constant.AuthConstants;
import com.powernode.constant.HttpConstants;
import com.powernode.model.Result;
import com.powernode.util.RedisCache;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author 梁卓
 * @Version 1.0
 * @ClassName LogoutSuccessHandlerImpl
 * @Description 登出成功处理器
 * @Date 2024/07/20 20:13
 */
@Component
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {

    @Resource
    private RedisCache redisCache;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 设置响应头
        response.setContentType(HttpConstants.APPLICATION_JSON);
        response.setCharacterEncoding(HttpConstants.UTF_8);
        // 获取token
        String authorization = request.getHeader(AuthConstants.AUTHORIZATION);
        String token = authorization.replaceFirst(AuthConstants.AUTHORIZATION_PREFIX, "");
        // 删除token
        redisCache.deleteObject(AuthConstants.LOGIN_TOKEN_PREFIX + token);
        // 响应结果
        Result<Object> result = Result.success(null);
        String resultStr = new ObjectMapper().writeValueAsString(result);
        PrintWriter writer = response.getWriter();
        writer.write(resultStr);
        writer.flush();
        writer.close();
    }
}
